######################
#  Replication code for 'Mediating the Electoral Connection', forthcoming in the JOP
#  John Henderson and John Brooks
#  12/7/2015    
######################    

# figure3-demx_analysis.R
#  :: runs slider iv results by incumbent electoral marginality for democrats

rm(list=ls())
setwd('~/Dropbox/rainReplication')   

# loop over data and fixed effects specifications 
non.missings = 4
fes.type = 3

source('prelimMain.R')

dprv_seq=c(0, 0.15, 0.25, 0.35, 0.45) 

coef1=coef2=matrix(NA,length(dprv_seq),3)      

for(i in 1:length(dprv_seq)){
		 
	if(i>=1 & i<length(dprv_seq)){
		flx=full[which(abs(d_prv)[full]>= dprv_seq[i] & abs(d_prv)[full]< dprv_seq[i+1])]
	} else if(i==length(dprv_seq)){
		flx=full[which(abs(d_prv)[full]>= dprv_seq[i])]
	}
	                  
	tmps=array(0,nrow(rain_data))  
	tmps[demx]=1
	tmps[-c(flx)]=0 
	flx=which(tmps==1)
	
main_iv1_fe=ivreg(vote~#as.factor(fe_id_num)+
	#d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose + dose_prv + vote_prv,
	~#as.factor(fe_id_num)+
	#d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose_prv + vote_prv + rain_day+rain_day_prev,
	subset=flx,data=covs) 
main_iv2_fe=ivreg(vote~
	#as.factor(fe_id_num)+
	#d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose + dose_prv + vote_prv,
	~#as.factor(fe_id_num)+
	#d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose_prv + vote_prv + rain_weekend+rain_weekend_prev,
	subset=flx,data=covs) 

main_iv1_fe_sum=summary(main_iv1_fe)
main_iv2_fe_sum=summary(main_iv2_fe)

main_iv1_fe_sumcl=coeftest.cluster(covs[flx,],main_iv1_fe,cluster1='as.factor(fe_id_num)')
main_iv2_fe_sumcl=coeftest.cluster(covs[flx,],main_iv2_fe,cluster1='as.factor(fe_id_num)') 

coef1[i,1:3]=main_iv1_fe_sum$coef[which(rownames(main_iv1_fe_sum$coef)=='dose'),c(1,2,4)]
coef2[i,1:3]=main_iv2_fe_sum$coef[which(rownames(main_iv2_fe_sum$coef)=='dose'),c(1,2,4)]
                    
}
 

save(
coef1,coef2,
file=paste('slider/figure3_demx-',non.missings,'_',fes.type,'.Rdata',sep=''))   

rm(
coef1,coef2
)
            
#detach(covs) 
#	}
#}    

# END      